<template>
  <div>
    <!-- 搜索页面头部 -->
    <div class="search-header">
      <!-- 后退按钮 -->
      <van-icon
        name="arrow-left"
        color="white"
        size="0.48rem"
        class="goback"
        @click="$router.back()"
      />
      <van-search
        v-model.trim="kw"
        v-fofo
        placeholder="请输入搜索关键词"
        background="#1989fa"
        shape="round"
        @input="inputFn"
        @search="searchFn"
      />
    </div>

    <!-- 搜索建议列表 -->
    <div class="sugg-list" v-if="kw.length !== 0">
      <div
        class="sugg-item"
        v-for="(item, index) in suggestionList"
        :key="index"
        v-html="lightFn(item, kw)"
        @click="suggestChickFn(item)"
      >
        <!-- 搜索建议 -->
      </div>
    </div>

    <!-- 搜索历史 -->
    <div class="search-history" v-else>
      <van-cell title="搜索历史">
        <!-- 使用right-icon 插槽来定义右侧图标 -->
        <template #right-icon>
          <van-icon name="delete" class="search-icon" @click="clearFn" />
        </template>
      </van-cell>

      <!-- 历史列表 -->
      <div class="history-list">
        <span
          class="history-item"
          v-for="(item, index) in history"
          :key="index"
          @click="historyChickFn(item)"
        >
          {{ item }}
        </span>
      </div>
    </div>
  </div>
</template>

<script>
import { getsuggestionListApi } from "@/api";
export default {
  data() {
    return {
      kw: "", //搜索关键词
      timer: null, //防抖的定时器
      suggestionList: [], //搜索结果联想列表
      history: JSON.parse(localStorage.getItem("his")) || [], //搜索历史
    };
  },
  methods: {
    //输入框内容变化时触发
    inputFn() {
      //防抖:延时执行逻辑代码，实际再次触发时，清除上一次定时器
      clearTimeout(this.timer); //清除定时器

      if (this.kw.length === 0) {
        this.suggestionList = [];
      } else {
        this.timer = setTimeout(async () => {
          if (this.kw.length === 0) return;
          // console.log(this.kw);
          const res = await getsuggestionListApi({
            keywords: this.kw,
          });
          this.suggestionList = res.data.data.options;
          // console.log(res, "搜索结果联想");
        }, 300);
      }
    },
    // 处理字符串高亮关键字
    lightFn(originItem, target) {
      // originItem:原来字符串
      // target:关键字
      // 字符串.replace()
      const reg = new RegExp(target, "ig"); //i忽略大小写,g全局都匹配
      return originItem.replace(reg, (match) => {
        return `<span style="color:red">${match}</span>`;
      });
    },

    moveFn(thekw) {
      setTimeout(() => {
        this.$router.push({
          path: `/search_result/${thekw}`,
        });
      }, 0);
    },

    //输入框的搜索事件
    searchFn() {
      if (this.kw.length > 0) {
        this.history.push(this.kw); //搜索关键字-保存到数组里
        this.moveFn(this.kw);
      }
    },
    // 联想菜单-点击事件
    suggestChickFn(item) {
      this.history.push(item); //搜索关键字-保存到数组里
      this.moveFn(item);
    },

    //历史列表-点击事件
    historyChickFn(item) {
      this.moveFn(item);
    },
    //清楚历史记录
    clearFn() {
      this.history = [];
    },
  },
  // watch监听器使用
  watch: {
    //历史记录数组的改变
    history: {
      deep: true,
      handler() {
        //数组去重 Set:无序不重复的value集合体
        //特点：你传入的数组类型，如果重复元素，会自动清理重复元素，返回五重复的Set对象
        const theSet = new Set(this.history);
        //Set类型对象 -> 转回 -> Arrer数组类型
        const arr = Array.from(theSet);
        //立刻覆盖式的保存到本地
        localStorage.setItem("his", JSON.stringify(arr));
      },
    },
  },
};
</script>

<style lang="less" scoped>
.search-header {
  height: 46px;
  display: flex;
  align-items: center;
  background: #1989fa;
  overflow: hidden;
  .goback {
    padding-left: 14px;
  }

  .van-search {
    flex: 1;
  }
}
.sugg-list {
  .sugg-item {
    padding: 0 15px;
    border-bottom: 1px solid #f8f8f8;
    font-size: 14px;
    line-height: 50px;
    // 实现省略号的三行代码
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

.search-history {
  .search-icon {
    font-size: 16px;
    line-height: inherit;
  }
  .history-list {
    padding: 0 10px;
    .history-item {
      display: inline-block;
      font-size: 12px;
      padding: 8px 14px;
      background: #efefef;
      margin: 10px 8px 0px 8px;
      border-radius: 10px;
    }
  }
}
</style>